import wx from '../../subwe/bridge';
import WXPage from "../../subwe/page";
import { Index } from '../../apis/index.js';
const app = getApp();
const API = new Index();
import CONST from '../../utils/const';
import util, { BluetoothMac, BluetoothPowerMinute } from '../../utils/util';
import { openBluetoothAdapterPeripheral } from '../../utils/bluetooth';
let computeOrderCostTime = null;
let bluetoothStatusTime = null;
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
WXPage({
  data: {
    // 客服电话
    callPhone: '400-818-7978',
    loginInfo: {},
    orderInfo: {},
    devInfo: {},
    orderCost: {
      t: '0',
      money: '0.00'
    },
    imageUrl: `${app.globalData.imageUrl}/zhongman2`
  },
  onLoad() {
    wx.setNavigationBarColor({
      frontColor: '#000000',
      backgroundColor: '#ffffff'
    });
    app.toPageServiceHome(true);
    this.getLoginToken();
  },
  // 呼叫服务
  callService() {
    if (!this.data.devInfo.serviceCall) return wx.showToast({
      title: '无服务电话',
      icon: 'error'
    });
    wx.showModal({
      title: '呼叫服务',
      content: `客服联系热线：${this.data.devInfo.serviceCall}`,
      confirmText: '立即呼叫',
      cancelColor: '#666',
      confirmColor: '#00A49AFF',
      success: res => {
        if (res.confirm) {
          this.makePhoneCall(this.data.devInfo.serviceCall);
        } else if (res.cancel) {
          console.log('用户点击取消');
        }
      }
    });
  },
  // 拨打电话
  makePhoneCall(phone) {
    wx.makePhoneCall({
      phoneNumber: phone,
      fail: err => {
        wx.showToast({
          title: '拨打电话失败',
          icon: 'none'
        });
      }
    });
  },
  // 登录
  getLoginToken() {
    API.getLoginToken().then(res => {
      if (!res) return;
      let loginInfo = res.result;
      this.setData({
        loginInfo: loginInfo
      });
      wx.setStorageSync("login_key", loginInfo);
      this.checkOrderStatus();
      this.getDeviceInfo();
    });
  },
  // 检查是否有订单
  checkOrderStatus() {
    let param = {
      "deviceSn": app.globalData.deviceSn,
      "openid": this.data.loginInfo.openid
    };
    API.checkOrderStatus(param).then(res => {
      const orderInfo = res.result;
      orderInfo.deviceSn = app.globalData.deviceSn;
      this.setData({
        orderInfo: orderInfo
      });
      this.computeOrderCost();
    });
  },
  // 获取设备信息
  getDeviceInfo() {
    let param = {
      "deviceSn": app.globalData.deviceSn
    };
    API.getDeviceInfo(param).then(res => {
      app.setBluetoothMac(res.result.bluetoothMac);
      this.setData({
        devInfo: res.result
      });
      wx.setStorageSync("showAd", res.result.isAd);
      this.computeOrderCost();
      computeOrderCostTime = setInterval(this.computeOrderCost.bind(this), 1000);
    });
  },
  // 计算订单时长与费用
  computeOrderCost() {
    if (this.data.orderInfo.state !== 2 || !this.data.devInfo.id || !this.data.orderInfo.id) {
      return clearInterval(computeOrderCostTime);
    }
    let timeLen = parseInt(new Date().getTime() / 1000 - this.data.orderInfo.beginAt);
    timeLen = timeLen > 0 ? timeLen : 0;
    let {
      h,
      m,
      s
    } = util.secondToTime(timeLen > 0 ? timeLen : 0);
    let t = `${h}时${m}分${s}秒`;
    let money = 0;
    for (let item of this.data.devInfo.ruleInfo) if (item.productId === this.data.orderInfo.productId) {
      if (this.data.orderInfo.feeMode === 1) {
        money = item.payIntervalPrice / (item.payInterval * 60) * timeLen;
        if (money > item.maxPayPrice) money = item.maxPayPrice;
        money = (money / 100).toFixed(2);
      } else money = (item.useDuration / 100).toFixed(2);
      break;
    }
    this.setData({
      orderCost: {
        t,
        money
      }
    });
  },
  // 蓝牙通知
  openBluetoothAdapterPeripheral(targetPowerMinute) {
    openBluetoothAdapterPeripheral({
      bluetoothMac: app.globalData.bluetoothMac,
      powerMinute: targetPowerMinute,
      success: res => {
        console.log('startAdvertising', res);
      }
    });
  },
  // 结束订单，结束使用
  closeOrder: function () {
    let loginInfo = wx.getStorageSync('login_key');
    wx.showModal({
      title: '小电温馨提示',
      content: '安全用电提醒：充电完毕后，请记得切断电源，将充电线放回方盒。它安全、您安心！充一次、美一次!',
      cancelText: '继续使用',
      confirmText: '立即归还',
      cancelColor: '#666',
      confirmColor: '#00A49AFF',
      success: res => {
        if (!res.confirm) return;
        let param = {
          "deviceSn": app.globalData.deviceSn,
          "productId": this.data.orderInfo.productId,
          "openid": loginInfo.openid,
          "tradeNo": this.data.orderInfo.tradeNo
        };
        API.closeOrder(param).then(res => {
          if (app.globalData.bluetoothMac) this.openBluetoothAdapterPeripheral(1);
          wx.redirectTo({
            url: '/pages/orderDetail/orderDetail?settMoney=' + res.result.settMoney + '&useTime=' + res.result.useTime + '&returnMoney=' + res.result.returnMoney + '&productId=' + this.data.orderInfo.productId + '&deviceSn=' + this.data.orderInfo.deviceSn
          });
        });
      }
    });
  },
  // 立即充电/继续充电
  orderToBack() {
    if (this.data.orderInfo.state === 2) {
      return wx.redirectTo({
        url: '/pages/cuse/cuse?devicesn=' + app.globalData.deviceSn
      });
    }
    return wx.redirectTo({
      url: '/pages/padline/padline?devicesn=' + app.globalData.deviceSn
    });
  },
  // 页面跳转
  pageGoto(url) {
    let info = {
      tradeNo: this.data.orderInfo.tradeNo || null,
      deviceSn: this.data.orderInfo.deviceSn || null,
      adderss: this.data.devInfo.room || null,
      placeId: this.data.devInfo.placeId || null,
      memberPhone: this.data.loginInfo.phone || null,
      placeName: this.data.devInfo.placeName || null
    };
    url = url + '?info=' + JSON.stringify(info);
    wx.navigateTo({
      url
    });
  },
  pageGotoSweep() {
    this.pageGoto("/pages/scendPages/serve/clean/clean");
  },
  pageGotoRepair() {
    this.pageGoto("/pages/scendPages/serve/repair/repair");
  },
  pageGotoArticles() {
    this.pageGoto("/pages/scendPages/serve/articles/articles");
  },
  pageGotoConrtnLive() {
    this.pageGoto("/pages/scendPages/serve/conrtnLive/conrtnLive");
  },
  pageGotoInvoice() {
    this.pageGoto("/pages/scendPages/serve/invoice/invoice");
  }
});